package 练习题;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Scanner;


/**
 * @author Liangyaoyun
 */
public class MyArrryList {
    public class MyArrayList<Integer> {
        //存储元素的数组
        private Integer[] array;
        //记录元素的总个数
        private int total = 0;
        public MyArrayList(int length) {
            //如果想手动设置大小，调用这个
            array = (Integer[]) new Object[length];
        }
        public MyArrayList() {
            //实例化数组,并且设置初始值是10
            this(10);
        }
        public void add(Integer e) {
            if (total >= array.length) {
                Integer[] newArray = (Integer[]) new Object[array.length + 10];
                for (int i = 0; i < array.length; i++) {
                    newArray[i] = array[i];
                }
                array = newArray;
                array[total] = e;
                total++;
            } else {
                array[total] = e;
                total++;
            }
        }
        public Integer get(int index) {
            if (index < total) {
                return array[index];
            } else {
                throw new ArrayIndexOutOfBoundsException("数组越界");
            }
        }
        public void printf(Integer[] nums){
            for (int i = 0; i < total; i++) {
                System.out.println(nums[i]);
            }
        }
    }
    @Test
    public void Test() {
        IntArrayList arrayList=new IntArrayList();
        Scanner scanner=new Scanner(System.in);
        System.out.print("请输入顺序表元素的个数:");
        int size= scanner.nextInt();
        System.out.print("请输入顺序表各个元素的值:");
        for (int i = 0; i < size; i++) {
            arrayList.add(scanner.nextInt());
        }
        arrayList.printf();
        System.out.print("请输出要删除元素的位置:");
        int i=scanner.nextInt();
        System.out.print("被删除的元素是:");
        System.out.println(arrayList.remove(i));
        System.out.print("被删除后的数组为:");
        arrayList.printf();
        System.out.print("请输入添加的元素:");
        i=scanner.nextInt();
        System.out.println();
        System.out.print("请输入添加元素的位置:");
        int index=scanner.nextInt();
        arrayList.add(i);
        arrayList.printf();
    }
}

